<%
-- all lua code provided by https://github.com/jow-/
-- thank you very much!

    function apply_acls(filename, session)
        local json = require "luci.jsonc"
        local util = require "luci.util"
        local fs   = require "nixio.fs"

        local grants = { }

        local acl = json.parse(fs.readfile(filename))
        if type(acl) ~= "table" then
            return
        end

        local group, perms
        for group, perms in pairs(acl) do
            local perm, scopes
            for perm, scopes in pairs(perms) do
                if type(scopes) == "table" then
                    local scope, objects
                    for scope, objects in pairs(scopes) do
                        if type(objects) == "table" then
                            if not grants[scope] then
                                grants[scope] = { }
                            end

                            if next(objects) == 1 then
                                local _, object
                                for _, object in ipairs(objects) do
                                    if not grants[scope][object] then
                                        grants[scope][object] = { }
                                    end
                                    table.insert(grants[scope][object], perm)
                                end
                            else
                                local object, funcs
                                for object, funcs in pairs(objects) do
                                    if type(funcs) == "table" then
                                        local _, func
                                        for _, func in ipairs(funcs) do
                                            if not grants[scope][object] then
                                                grants[scope][object] = { }
                                            end
                                            table.insert(grants[scope][object], func)
                                        end
                                    end
                                end
                            end
                        end
                    end
                end
            end
        end

        local _, scope, object, func
        for scope, _ in pairs(grants) do
            local objects = { }
            for object, _ in pairs(_) do
                for _, func in ipairs(_) do
                    table.insert(objects, { object, func })
                end
            end

            util.ubus("session", "grant", {
                ubus_rpc_session = session,
                scope = scope, objects = objects
            })
        end
    end

    apply_acls("/usr/share/rpcd/acl.d/attendedsysupgrade.json", luci.dispatcher.context.authsession)
    apply_acls("/usr/share/rpcd/acl.d/packagelist.json", luci.dispatcher.context.authsession)
%>
<%+header%>
<h2 name="content"><%:Attended Sysupgrade%></h2>
<div class="container">
	<div style="display: none" id="update_info" class="alert-message info"></div>
	<div style="display: none" id="update_error" class="alert-message danger"></div>
</div>
<input class="cbi-button" value="search for updates" onclick="update_request()" type="button" id="update_button">
<div style="display: none" id="packages" class="alert-message success"></div>
<div class="cbi-value" id="update_packages_container" style="display: block">
	<label class="cbi-value-title" for="keep">search for package updates:</label>
	<div class="cbi-value-field">
		<input type="checkbox" name="update_packages" id="update_packages" />
	</div>
</div>
<div class="cbi-value" id="keep_container" style="display: none">
	<label class="cbi-value-title" for="keep">keep settings:</label>
	<div class="cbi-value-field">
		<input type="checkbox" name="keep" id="keep" checked="checked" />
	</div>
</div>

<script type="text/javascript">

latest_version = "";
data = {};
ubus_counter = 1
origin = document.location.href.replace(location.pathname, "")
ubus_url = origin + "/ubus/"

// requests to the update server
function server_request(request_dict, path, callback) {
	url = data.update_server + "/" + path
	request_dict.distro = data.release.distribution;
	request_dict.target = data.release.target.split("\/")[0];
	request_dict.subtarget = data.release.target.split("\/")[1];
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.open("POST", url, true);
	xmlhttp.setRequestHeader("Content-type", "application/json");
	xmlhttp.send(JSON.stringify(request_dict));
	xmlhttp.onerror = function(e) {
		update_error("update server down")
	}
	xmlhttp.addEventListener('load', function(event) {
		callback(xmlhttp)
	});
}

// requests ubus via rpcd
function ubus_request(command, argument, params, callback) {
	request_data = {};
	request_data.jsonrpc = "2.0";
	request_data.id = ubus_counter;
	request_data.method = "call";
	request_data.params = [ data.ubus_rpc_session, command, argument, params ]
	ubus_counter++
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.open("POST", ubus_url, true);
	xmlhttp.setRequestHeader("Content-type", "application/json");
	xmlhttp.onerror = function(e) {
		setTimeout(back_online, 5000)
	}
	xmlhttp.addEventListener('load', function(event) {
		if(command === "uci") {
			ubus_request_callback_uci(xmlhttp, callback)
		} else {
			ubus_request_callback(xmlhttp, callback)
		}
	});
	xmlhttp.send(JSON.stringify(request_data));
}

// handle ubus_requests, set variables or perform functions
function ubus_request_callback(response_object, callback) {
	if(response_object.status === 200) {
		console.log(callback)
		if(typeof callback === "string") {
			response_json = JSON.parse(response_object.responseText).result[1]
			if (callback == "release") {
				latest_version = response_json.release.version
			}
			data[callback] = response_json[callback]
		} else {
			callback(response_object)
		}
	} else {
		console.log(respons_object.responseText)
	}
}

function ubus_request_callback_uci(response_object, callback) {
	if(response_object.status === 200) {
		console.log(callback)
		response_json = JSON.parse(response_object.responseText).result[1].value
		data[callback] = response_json

		document.getElementById("update_packages").checked = data.update_packages;
	} else {
		console.log(respons_object.responseText)
	}
}

// initial setup, get system information
function setup() {
	data["ubus_rpc_session"] = "<%=luci.dispatcher.context.authsession%>"
	ubus_request("packagelist", "list", {}, "packagelist");
	ubus_request("system", "board", {}, "release");
	ubus_request("system", "board", {}, "board_name");
	ubus_request("system", "board", {}, "model");
	ubus_request("uci", "get", { "config": "attendedsysupgrade", "section": "updateserver", "option": "url" }, "update_server")
	ubus_request("uci", "get", { "config": "attendedsysupgrade", "section": "updateclient", "option": "update_packages" }, "update_packages")
}

// shows notification if update is available
function update_info(info_output) {
	document.getElementById("update_info").style.display = "block";
	document.getElementById("update_info").innerHTML = info_output;
}

function update_error(error_output) {
	document.getElementById("update_error").style.display = "block";
	document.getElementById("update_error").innerHTML = error_output;
	document.getElementById("update_info").style.display = "none";
}

// asks server for news updates, actually only based on relesae not packages
function update_request() {
	console.log("update_request")
	request_dict = {}
	request_dict.version = data.release.version;
	request_dict.packages = data.packagelist;
	if (document.getElementById("update_packages").checked == 1) {
		request_dict.update_packages = 1
	}
	server_request(request_dict, "update-request", update_request_callback)
}

function update_request_callback(response_object) {
	if (response_object.status === 500) {
		// python crashed
		update_error("internal server error, please try again later")
		console.log("update server issue")
	} else if (response_object.status === 502) {
		// python part offline
		update_error("internal server error, please try again later")
		console.log("update server issue")
	} else if (response_object.status === 503) {
		// handle overload
		update_error("server overloaded, retry in 5 minutes")
		console.log("server overloaded")
		setTimeout(update_request, 300000)
	} else if (response_object.status === 201) {
		update_info("imagebuilder not ready, please wait")
		console.log("setting up imagebuilder")
		setTimeout(update_request, 5000)
	} else if (response_object.status === 204) {
		// no updates
		update_info("no updates available")
	} else if (response_object.status === 400) {
		// bad request
		console.log(response_object.responseText)
		response_object_content = JSON.parse(response_object.responseText)
		update_error(response_object_content.error)
	} else if (response_object.status === 200) {
		// new release/updates
		response_object_content = JSON.parse(response_object.responseText)
		update_request_200(response_object_content)
	}
}

function back_online() {
	ubus_request("session", "login", {}, back_online_callback)
}

function back_online_callback(response_object) {
	if (response_object.status != 200) {
		setTimeout(back_online, 5000)
	} else {
		update_info("upgrade successfull!")
		document.getElementById("update_button").value = "reload page";
		document.getElementById("update_button").onclick = function() { location.reload(); }
	}

}

function update_request_200(response_content) {
	info_output = ""
	if(response_content.version != undefined) {
		info_output += "<h3>new update available</h3>"
		info_output += data.release.version + " to " + response_content.version
		latest_version = response_content.version;
	}
	if(response_content.updates != undefined) {
		info_output += "<h3>package updates available</h3>"
		for (update in response_content.updates) {
			info_output += "<b>" + update + "</b>: " + response_content.updates[update][1] + " to " + response_content.updates[update][0] + "</br>"
		}
	}
	data.packages = response_content.packages
	update_info(info_output)
	document.getElementById("update_button").value = "request image";
	document.getElementById("update_packages_container").style.display = "none";
	document.getElementById("update_button").onclick = image_request;
}

// request the image, need merge with update_request
function image_request() {
	console.log("image_request")
	document.getElementById("update_packages_container").style.display = "none";
	request_dict = {}
	request_dict.version = latest_version;
	request_dict.board = data.board_name
	request_dict.packages = data.packages;
	request_dict.model = data.model
	server_request(request_dict, "image-request", image_request_handler)
}

function image_request_handler(response) {
	if (response.status === 400) {
		response_content = JSON.parse(response.responseText)
		update_error(response_content.error)
	} else if (response.status === 500) {
		image_request_500()
	} else if (response.status === 503) {
		update_error("please wait. server overloaded")
		// handle overload
		setTimeout(image_request, 30000)
	} else if (response.status === 201) {
		response_content = JSON.parse(response.responseText)
		if(response_content.queue != undefined) {
			// in queue
			update_info("please wait. you are in queue position " + response_content.queue)
			console.log("queued")
		} else {
			update_info("imagebuilder not ready, please wait")
			console.log("setting up imagebuilder")
		}
		setTimeout(image_request, 5000)
	} else if (response.status === 206) {
		// building
		console.log("building")
		update_info("building image")
		setTimeout(image_request, 5000)
	} else if (response.status === 200) {
		// ready to download
		response_content = JSON.parse(response.responseText)
		update_info("image created")
		document.getElementById("update_button").value = "sysupgrade"
		document.getElementById("update_button").onclick = function() {download_image(response_content.url); }
		document.getElementById("keep_container").style.display = "block";
	}
}


// uploads received blob data to the server using cgi-io
function upload_image(blob) {
	var upload_request = new XMLHttpRequest();
	var form_data  = new FormData();

	form_data.append("sessionid", data.ubus_rpc_session)
	form_data.append("filename", "/tmp/sysupgrade.bin")
	form_data.append("filemode", 755) // insecure?
	form_data.append("filedata", blob)

	upload_request.addEventListener('load', function(event) {
		// this checksum should be parsed
		document.getElementById("update_info").innerHTML = "flashing... please wait" // show fancy indicator http://www.ajaxload.info/

		ubus_request("attendedsysupgrade", "sysupgrade", { "keep_settings": document.getElementById("keep").checked }, 'done');
  	});

  	upload_request.addEventListener('error', function(event) {
		document.getElementById("update_info").innerHTML = "uploading failed, please retry"
  	});

  	upload_request.open('POST', origin + '/cgi-bin/cgi-upload');
  	upload_request.send(form_data);
}

// download image from server once the url was received by image_request
function download_image(url) {
	console.log("download_image")
	document.getElementById("update_button").value = "flashing..."
	document.getElementById("update_button").disabled = true;
	var download_request = new XMLHttpRequest();
	download_request.open("GET", url);
	download_request.responseType = "arraybuffer";

	download_request.onload = function () {
		if (this.status === 200) {
			var blob = new Blob([download_request.response], {type: "application/octet-stream"});
			upload_image(blob)
		}
	};
	document.getElementById("update_info").innerHTML = "downloading image"
	download_request.send();
}

document.onload = setup()
</script>

<%+footer%>
